package com.example.cloudsamplegateway.filter;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.common.jwt.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String[] skipUrl = {"/provider/login"};
    @Autowired
    private AntPathMatcher antPathMatcher;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.error("---- {} ---", path);
        for (String skip : skipUrl) {
            if (antPathMatcher.match(skip, path)) {
                return chain.filter(exchange);
            }
        }
//        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
//        if (StringUtils.isBlank(token)) {
//            log.error("----- 验证没有通过 ----");
//            return error(exchange, "没有登录，请登录");
//        } else {
//            try {
//                Jws<Claims> claimsJws = JwtUtils.parserToken(token);
//                Claims body = claimsJws.getBody();
//                LocalDateTime expiration = LocalDateTime.ofInstant(body.getExpiration().toInstant(), ZoneId.systemDefault());
//
//                if (expiration.isAfter(LocalDateTime.now())) {
//                    return chain.filter(exchange);
//                } else {
//                    return error(exchange, "登录过期了！");
//                }
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//                return error(exchange, "认证失败," + e.getMessage());
//            }
//        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> error(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "500");
        jsonObject.put("msg", msg);
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");

        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toString().getBytes());

        return response.writeWith(Mono.just(wrap));
    }
}
